﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;

namespace Medianamik.UI
{
    public class UserControlRenderer
    {
        public static string RenderUserControl(string path,
            Dictionary<string, object> propertyValues)
        {
            var pageHolder = new Page();
            var viewControl = GetControl(pageHolder, path, propertyValues);
            pageHolder.Controls.Add(viewControl);
            var output = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, output, false);

            return output.ToString();
        }

        public static UserControl GetControl(Page pageHolder, string path, Dictionary<string, object> propertyValues)
        {
            var viewControl = (UserControl)pageHolder.LoadControl(path);
            var viewControlType = viewControl.GetType();

            foreach (var kvp in propertyValues)
            {
                var property = viewControlType.GetProperty(kvp.Key);

                if (property != null)
                {
                    property.SetValue(viewControl, kvp.Value, null);
                }
                else
                {
                    throw new Exception(string
                        .Format("UserControl: {0} does not have a public {1} property.", path, kvp.Key));
                }
            }

            return viewControl;
        }
    }
}
